package hongcheng.code_generator.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import cn.hutool.core.util.StrUtil;
import hongcheng.code_generator.exception.CustomException;

/**
 * 	数据库连接工具
 * */
public class DBManager {

	
	private String url;
	
	private String userName;
	
	private String password;
	
	private Connection connection;
	
	private Statement statement;
	
	private ResultSet resultSet;
	
	public DBManager(String url,String userName,String password) {
		this.url = url;
		this.userName = userName;
		this.password = password;
	}
	
	
	/**
	 * 	连接
	 * */
	public void connection() throws Exception {
		if(connection != null) {
			return;
		}
		//1.注册驱动(静态方法)(包名+类名）jdbc4.0以上不需要了
		//2.获取连接对象(导包都导sql里面的，不导jdbc里的；多态！报异常是因为用户输入的串可能写错）后面设置下数据格式
        connection = DriverManager.getConnection(url,userName,password);
        
	}
	
	
	/**
	 * 	执行sql
	 * */
	public ResultSet executeQuery(String sql) throws Exception {
		if(StrUtil.isBlank(sql)) {
			throw new CustomException("SQL语句为空");
		}
		// 执行下连接，防止未连接数据库就执行sql
		this.connection();
		Statement statement = connection.createStatement();
		// 执行sql
		resultSet = statement.executeQuery(sql);
		return resultSet;
	}
	

	
	
	/**
	 * 	关闭
	 * */
	public void close() {
		if(this.resultSet != null) {
			try {
				this.resultSet.close();
			}catch(Exception e1) {
				
			}finally {
				if(this.statement != null) {
					try {
						this.statement.close();
					}catch(Exception e2) {
						
					}finally {
						if(this.connection != null) {
							try {
								this.connection.close();
							}catch(Exception e3) {
								
							}
						}
					}
				}
			}
		}
	}


	


	public String getUrl() {
		return url;
	}


	public void setUrl(String url) {
		this.url = url;
	}


	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public Connection getConnection() {
		return connection;
	}


	public void setConnection(Connection connection) {
		this.connection = connection;
	}


	public Statement getStatement() {
		return statement;
	}


	public void setStatement(Statement statement) {
		this.statement = statement;
	}


	public ResultSet getResultSet() {
		return resultSet;
	}


	public void setResultSet(ResultSet resultSet) {
		this.resultSet = resultSet;
	}
	
	
	
	
	
	
}
